package com.mujin.keji.collectionsystem.module.sign.views;

import android.Manifest;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.sign.dapter.SignDayContentdAdapter;
import com.mujin.keji.collectionsystem.module.sign.dapter.SignDaydAdapter;
import com.mujin.keji.collectionsystem.module.sign.dto.DaysDto;
import com.mujin.keji.collectionsystem.module.sign.dto.ShowSignDaysDto;
import com.mujin.keji.collectionsystem.module.sign.dto.SignDateDto;
import com.mujin.keji.collectionsystem.module.sign.viewmodel.SignViewModel;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.permissions.PermissionUtils;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.utils.DateUtil;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.DisplayUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.widget.CustomerItemDecoration;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 签到Activity界面
 *
 * @author weishixiong
 * @Time 2018-03-22
 */

public class SignActivity extends BaseActivity implements View.OnClickListener, BDLocationListener, CustomItemClickListener, SignDaydAdapter.SignClikListener {
    private SignViewModel signViewModel;
    private RecyclerView rvDate;
    private GridLayoutManager gridLayoutManager;
    private List<DaysDto> datas;
    private SignDaydAdapter signDaydAdapter;
    private TextView tvNow;
    private ImageView ivLeft;
    private ImageView ivRight;
    private TextView tvHasSignDays;
    private TextView tvNoSignDays;
    //private ImageView ivSign;
    private int year;
    private int month;
    private String nowDayStr;//今天年月日 字符
    private String selectDayStr;//选择的年月日字符串
    private int startCount;//前半部分数量
    private int centerCount;//中间部分数量
    private int afterCount;//后半部分数量
    private List<ShowSignDaysDto> signDays;//签到的日数
    private String mAddress;//定位到的当前地址
    //private TextView tvContent;
    private TextView tvSign;
    private RecyclerView rvSignContent;
    private SignDayContentdAdapter signDayContentdAdapter;
    private LinearLayoutManager linearLayoutManager;
    private RelativeLayout rlNoSign;


    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.getInstance().mLocationClient.stop();
        CcsApplication.getInstance().mLocationClient.unRegisterLocationListener(this);
        CcsApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        signViewModel = ViewModelProviders.of(this).get(SignViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_sign;
    }

    @Override
    public void initView() {
        rvSignContent = (RecyclerView) findViewById(R.id.rv_sign_content);
        nowDayStr = DateUtil.coverDateFormat(DateUtil.DATE_FORMAT_, new Date());
        setCenterTitle("签到", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        tvNow = (TextView) findViewById(R.id.tv_now);
        rvDate = (RecyclerView) findViewById(R.id.rv_date);
        ivLeft = (ImageView) findViewById(R.id.iv_left);
        ivRight = (ImageView) findViewById(R.id.iv_right);
        tvHasSignDays = (TextView) findViewById(R.id.tv_has_sign_days);
        tvNoSignDays = (TextView) findViewById(R.id.tv_no_sign_days);
        tvSign = (TextView) findViewById(R.id.tv_sign);
        // tvContent = (TextView) findViewById(R.id.tv_content);
        gridLayoutManager = new GridLayoutManager(this, 7);
        rvDate.setLayoutManager(gridLayoutManager);
        datas = new ArrayList<>();
        signDaydAdapter = new SignDaydAdapter(this, datas, this);
        rvDate.setAdapter(signDaydAdapter);
        initDaysData();
        contentList = new ArrayList<>();
        signDayContentdAdapter = new SignDayContentdAdapter(this, contentList);
        linearLayoutManager = new LinearLayoutManager(this);
        rvSignContent.setLayoutManager(linearLayoutManager);
        rvSignContent.setAdapter(signDayContentdAdapter);
        rvSignContent.addItemDecoration(new CustomerItemDecoration(DisplayUtil.dip2px(this, 8)));
        rlNoSign = (RelativeLayout) findViewById(R.id.rl_no_sign);

    }


    private void initDaysData() {
        //获取当前年月
        Calendar now = Calendar.getInstance();
        year = now.get(Calendar.YEAR);
        month = (now.get(Calendar.MONTH) + 1);
        initYearsMonthsData();
    }

    //private List<SignDateDto> signDateDtoList;
    private Map<String, List<SignDateDto>> dateMap;
    private List<Integer> signDaysInteger;//临时变量 用来判断

    /**
     * 根据年月展示日历
     */
    private void initYearsMonthsData() {

          ToastUtils.showToast("暂未开放");
          return;
//        dateMap = new HashMap<>();
//        //signDateDtoList = new ArrayList<>();
//        initSelectDayStr(year, month);
//        signDays = new ArrayList<>();
//        datas.clear();
//        tvNow.setText(year + "年" + month + "月");
//        //获取当前年月的天数
//        int nowDays = DateUtil.getMonthLastDay(year, month);
//        //获取上个月的天数
//        int lastDays = DateUtil.getMonthLastDay(year, month);
//        //获取本月第一天的date对象
//        final Date date = DateUtil.getMonthIndexDate(year, month, 1);
//        //获取本月第一天是星期几
//        int weekOfDate = DateUtil.getWeekOfDateIndex(date);
//        if (weekOfDate == 0) {
//            weekOfDate = 7;
//        }
//        //计算上个月一共有多少天
//        for (int i = 1; i < weekOfDate; i++) {
//            datas.add(new DaysDto(lastDays + 1 - i, false, false, false, false, null, false));
//        }
//        startCount = weekOfDate - 1;
//        centerCount = nowDays;
//        afterCount = 42 - startCount - centerCount;
//
//        for (int i = 1; i <= nowDays; i++) {
//            if (i < 10) {
//                selectDayStr += "-" + ("0" + i);
//            } else {
//                selectDayStr += "-" + i;
//            }
//            if (selectDayStr.equals(nowDayStr)) {
//                datas.add(new DaysDto(i, true, false, false, true, null, true));
//            } else {
//
//                datas.add(new DaysDto(i, false, false, false, true, null, false));
//            }
//            initSelectDayStr(year, month);
//        }
//        for (int i = 1; i <= afterCount; i++) {
//            datas.add(new DaysDto(i, false, false, false, false, null, false));
//        }
//        signDaydAdapter.notifyDataSetChanged();
//
//
//        signViewModel.getSignDetailLiveData(year + "-" + (month < 10 ? ("0" + month) : (month + "")), this).observe(this, new Observer<BaseDto<SignDetailDto>>() {
//            @Override
//            public void onChanged(@Nullable BaseDto<SignDetailDto> signDetailDtoBaseDto) {
//                try {
//                    if (signDetailDtoBaseDto.getCode() == Constant.Server.SUCCESS_CODE && signDetailDtoBaseDto.getData() != null) {
//                        // signDateDtoList.addAll(signDetailDtoBaseDto.getData().getSignDate());
//                        dateMap.clear();
//                        tvNoSignDays.setText(signDetailDtoBaseDto.getData().getNoSignCount() + "天 /本月未签到");
//                        tvHasSignDays.setText(signDetailDtoBaseDto.getData().getSignCount() + "天 /本月已签到");
//                        if (EmptyUtils.isNotEmpty(signDetailDtoBaseDto.getData().getDateMap())) {
//                            dateMap.putAll(signDetailDtoBaseDto.getData().getDateMap());
//                            for (String key : signDetailDtoBaseDto.getData().getDateMap().keySet()) {
//                                String signDay = key.split("-")[2];
//                                Integer signDatInt = Integer.parseInt(signDay);
//                                //获取到签到的日
//                                signDays.add(new ShowSignDaysDto(signDatInt, signDetailDtoBaseDto.getData().getDateMap().get(key)));
//                            }
//                        }
//                        signDaysInteger = new ArrayList<>();
//                        for (int i = 0; i < signDays.size(); i++) {
//                            signDaysInteger.add(signDays.get(i).getSignDay());
//                        }
//                        int k = 0;
//                        for (int i = startCount + 1; i <= centerCount + startCount; i++) {
//                            if (signDaysInteger.contains(datas.get(i - 1).getDay())) {
//                                datas.get(i - 1).setSign(true);
//                                datas.get(i - 1).setAdress(signDays.get(k).getAdress());
//                                k++;
//                            }
//                        }
//                        signDaydAdapter = new SignDaydAdapter(SignActivity.this, datas, SignActivity.this);
//                        rvDate.setAdapter(signDaydAdapter);
//
//                    }
//                    //当天的签到记录
//
//                    for (int i = 0; i < datas.size(); i++) {
//                        if (datas.get(i).isNowDay()) {
//                            onSignClick(datas.get(i));
//                        }
//                    }
//                } catch (Exception e) {
//                }
//
//            }
//        });


    }


    private void initSelectDayStr(int year, int month) {
        selectDayStr = String.valueOf(year);
        if (month < 10) {
            selectDayStr += "-" + ("0" + month);
        } else {
            selectDayStr += "-" + month;
        }
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        getLocationSetting();
        getPermission();
    }

    private void getPermission() {
        //获取定位权限
        RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {
                //开启定位
                CcsApplication.getInstance().mLocationClient.start();
                CcsApplication.getInstance().mLocationClient.registerLocationListener(SignActivity.this);
            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                if (!PermissionUtils.hasPermission(SignActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, SignActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(SignActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, SignActivity.this);
                    return;
                }


            }
        });
    }

    /**
     * 打开位置设置
     */
    private void getLocationSetting() {
        if (!NetworkUtil.isGpsOPen(this)) {
            CcsApplication.getInstance().mLocationClient.stop();
            //位置信息没有开启
            DialogUtils.showAdressInfoDailog("无法获取当前位置信息，请在手机设置中开启位置信息", SignActivity.this);
            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            //startActivity(intent);
            return;
        }
    }
    /**
     * 签到接口
     *
     * @param signAddress
     * @param signDate
     * @param source
     */
    private void sign(String signAddress, String signDate, String source) {
        getLoadingDialog().showDialog();
        signViewModel.getSignLiveData(signAddress,signDate,source,this).observe(this,signDtoBaseDto -> {
            getLoadingDialog().dismiss();
            if (signDtoBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
                ToastUtils.showToast("签到成功");
                initDaysData();
            } else {
                ToastUtils.showToast(signDtoBaseDto.getMsg());
            }
        });
    }

    @Override
    public void initListener() {
        ivLeft.setOnClickListener(this);
        ivRight.setOnClickListener(this);
        tvSign.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                month--;
                if (month == 0) {
                    month = 12;
                    year--;
                }
                initYearsMonthsData();
                contentList.clear();
                signDayContentdAdapter.notifyDataSetChanged();
                break;
            case R.id.iv_right:
                month++;
                if (month == 13) {
                    month = 1;
                    year++;
                }
                initYearsMonthsData();
                contentList.clear();
                signDayContentdAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_sign:
                if (TextUtils.isEmpty(mAddress)) {
                    ToastUtils.showToast("未获取到当前地址，请稍后再试");
                    return;
                }
                sign(mAddress, DateUtil.coverDateFormat(DateUtil.DATE_FORMAT_, new Date()), "2");
                break;

        }

    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            //获取定位地址
            mAddress = bdLocation.getAddrStr();
            CcsApplication.getInstance().mLocationClient.stop();

        }
    }

    @Override
    public void onItemClick(View view, int position) {

    }

    private List<String> contentList;//签到内容

    @Override
    public void onSignClick(DaysDto daysDto) {
        if (!daysDto.isNowMonth()) {
            return;
        }
        contentList.clear();
        int index = datas.indexOf(daysDto);
        for (int i = 0; i < datas.size(); i++) {
            if (index == i) {
                datas.get(i).setSelected(true);
            } else {
                datas.get(i).setSelected(false);
            }
        }
        signDaydAdapter.notifyDataSetChanged();
        if (EmptyUtils.isNotEmpty(daysDto.getAdress())) {
            for (int i = 0; i < daysDto.getAdress().size(); i++) {
                if (TextUtils.isEmpty(daysDto.getAdress().get(i).getSignAddress())) {
                    break;
                }
                String content = daysDto.getAdress().get(i).getTime() + " 在" + (((daysDto.getAdress().get(i).getSignAddress()).contains("中国")) ? (daysDto.getAdress().get(i).getSignAddress().replace("中国", "")) : (daysDto.getAdress().get(i).getSignAddress())) + "外访并完成签到。";
                contentList.add(content);
            }
        }
        if(EmptyUtils.isNotEmpty(contentList)){
            rlNoSign.setVisibility(View.GONE);
            rvSignContent.setVisibility(View.VISIBLE);
        }
        else{
            rlNoSign.setVisibility(View.VISIBLE);
            rvSignContent.setVisibility(View.GONE);
        }
        signDayContentdAdapter.notifyDataSetChanged();
    }
}
